package org.swan.web.role.service.impl;

import org.springframework.stereotype.Service;
import org.stream.tool.db.ADOConnection;
import org.swan.web.exception.BusinessCode;
import org.swan.web.exception.BusinessException;
import org.swan.web.role.bean.RolePermissionBean;
import org.swan.web.role.mapper.RolePermissionMapper;
import org.swan.web.role.service.RolePermissionService;
import java.util.List;
import java.util.Optional;

@Service
public class RolePermissionServiceImpl implements RolePermissionService {

    public RolePermissionServiceImpl() {
    }

    @Override
    public Optional<RolePermissionBean> getRolePermissionById(long id) {
        if (id == -1L)
            return Optional.of(RolePermissionBean.SAMPLE);
        return ADOConnection.runTask(factory -> factory.getMapper(RolePermissionMapper.class).getById(id), Optional.class);
    }

    @Override
    public long addRolePermission(RolePermissionBean rolePermissionBean) {
        long result = ADOConnection.runTask(factory -> factory.getMapper(RolePermissionMapper.class).add(rolePermissionBean), Long.class);
        return result;
    }

    @Override
    public RolePermissionBean updateRolePermission(RolePermissionBean rolePermissionBean) {
        getRolePermissionById(rolePermissionBean.getRolePermissionId()).orElseThrow(() -> new BusinessException(BusinessCode.ROLE_PERMISSION_DO_NOT_EXIST, rolePermissionBean.getRolePermissionId()));
        ADOConnection.runTask(factory -> factory.getMapper(RolePermissionMapper.class).updateById(rolePermissionBean), Long.class);
        return getRolePermissionById(rolePermissionBean.getRolePermissionId()).get();
    }

    @Override
    public RolePermissionBean deleteRolePermissionById(long rolePermissionId) {
        RolePermissionBean rolePermissionBean = getRolePermissionById(rolePermissionId).orElseThrow(() -> new BusinessException(BusinessCode.ROLE_PERMISSION_DO_NOT_EXIST, rolePermissionId));
        ADOConnection.runTask(factory -> factory.getMapper(RolePermissionMapper.class).deleteById(rolePermissionId), Long.class);
        return rolePermissionBean;
    }

    @Override
    public List<RolePermissionBean> list(int offset, int rows) {
        return ADOConnection.runTask(factory -> factory.getMapper(RolePermissionMapper.class).list(offset, rows), List.class);
    }
}
